<?php
App::import('vendor','paginator');
class PagesController extends AppController
{
	var $name            = "Pages";
	var $uses            = array('Page','Ajax','Cron','Cache', 'Login');
	var $components      = array('Session');
	var $metaDescription = "";
	var $metaKeywords    = "";
	var $layout          = "default";
	var $currency        = "&euro;";
	
	function getChat(){
		if(! $this->Session->check('logged')){
			$this->redirect('/'.U_HOME);
		}
		if(!$this->Session->read('last_chat_id')){
			$this->Session->write('last_chat_id',0);
		}
		$last_chat_id = (int)($this->Session->read('last_chat_id'));
		$chat_id = ($last_chat_id>=50?$last_chat_id-50:0);
		$game_id = $this->Session->read('game_id');		
		$get_the_last = $this->Ajax->readLast50Chats((int)$chat_id,"",$game_id);
		
		if(count($get_the_last)>0){  
			$chatstr = "";
			foreach($get_the_last as $last){
				$chatstr .= "$(\".chat div\").append(\"<p><small>(<a href=\'".U_PROFILES."#profile{$last['user_id']}\'>".
					"{$last['user_id']}&rsaquo;{$last['nickname']}</a>)</small> ".
					" &gt; <strong>{$last['message']}</strong></p>\");";			
			}
			return $chatstr."";
    	} else {
    	 	return "";
    	}	
    }
	
    function beforeFilter(){
		//redirect if the user is not logged in________________________________	
    	parent::beforeFilter();
		if(!$this->Session->check('logged')){
			$this->redirect(U_HOME);
		} 
    }
	
	function beforeRender(){
		parent::beforeRender();
		//this clears ALL the cache____________________________________________
//		Cache::clear();
		//get the game id and location info____________________________________
		$game_id = $this->Session->read('game_id');
		$this->set('game',$this->Page->getGameInfo($game_id));
		
		//get the chat_______________________________________________________
		$this->set('chat_string',$this->getChat());
		
		//get the news for the current user____________________________________
		$id = $this->Session->read('logged');
		$news = $this->Page->getNews($id,$game_id);
		if(!empty($news)) {
			$this->set('news',$news);
		}	
		$this->set('currency',$this->currency);
		//get user information_________________________________________________
		$user_info = $this->Page->userInformation($id);
		$user_info['net_worth'] = $this->Cron->getUserRanking($id);
		$this->set('user_info', $user_info);
		//get all buildings type (for js => markers)___________________________
		$btypes      = $this->Ajax->getDataTypes("building_type");
		$build_types = "var btype = new Array()\n";
		for($i=0;$i<count($btypes);$i++) {
			$build_types .= "btype[{$i}] = '{$btypes[$i]}';\n";
		}
		$this->set('btypes', $build_types);
	}

	function signOut(){
		$this->Login->signOut($this->Session->read('logged'));
		$this->Session->del('logged');
		$this->Session->del('game_id');
		$this->Session->del('last_chat_id');	
		$this->redirect(U_HOME);
	}
	//see the prices and select the property
	function selectProperty(){
		$this->set('user_id', $this->Session->read('logged'));
		$game_id = $this->Session->read('game_id');
		$this->set('xml_file', "MarkerData{$game_id}.xml");
		$this->metaDescription = 'Select Property '.T_SITE_TITLE; 
		$this->metaKeywords = 'Select Property '.T_SITE_TITLE;
		$this->pageTitle = 'Select Property ';
		
		$statistics = $this->Page->getGameStatistics($game_id);
		$this->set('game_name',$statistics['game_name']);
		$this->set('city_name',$statistics['city_name']);
		$this->set('game_time',$statistics['game_time']);
		$this->set('game_time_max',$statistics['game_time_max']);
		$this->set('total_population',$statistics['total_population']);
	}
	
	function buyCreateProperty($lat, $long, $bcond){
		$game_id = $this->Session->read('game_id');
		$btype = $this->Ajax->getDataTypes("building_type");
		$this->set('btype',$btype);
		$this->pageTitle = "Buy Property";
		
		$region = $this->Ajax->getRegion($lat,$long,$game_id);				
		$this->set('region',$region);
		$this->set('bcond',$bcond);
			
		$message = "";
		$id = $this->Session->read('logged');				
		if(isset($this->params['form']) && !empty($this->params['form'])){
			$required = array('property_name'=>"name for the property", "building_type"=>"a building type");
			foreach($required as $req=>$mess){
				if(!isset($this->params['form'][$req]) || empty($this->params['form'][$req])){
					$message .= "- Please select {$mess}.<br/>";
				}
			}
			$is_afford = $this->Page->affordable($this->params['form']['bprice'],$id); 
			if(!empty($is_afford)) {
				$message = $is_afford;
			}
			if (empty($message)) {			
				$message = $this->Page->isPropertyThere($lat,$long,$id,$game_id);
			}
			if (empty($message)) {					
				$revenue = $this->Cron->getValue4Revenue($bcond, $region['region_worth'],
					$this->params['form']['building_type'], $region['region_id']);
				$this->Page->addProperty($this->params['form'],$lat,$long, 
										$bcond,$id,$region,$revenue);
				unset($this->params['form']);
				$this->set('message','Property succesfully bought!');
			} else {
				$this->set('message',$message);	
			}
		}
		$this->requestAction('/Cron/createMarkers/');
	}	
	
	function upgradeProperty($marker_id, $user_id){
		$curr_id = $this->Session->read('logged');
		if($user_id != $curr_id) {
			$this->redirect(U_HOME.UC_MAP);
		}
		$game_id = $this->Session->read('game_id');
		$prop_info = $this->Cron->getMarkers($game_id,$user_id,$marker_id);
		if(count($prop_info)<1){
			$this->redirect(U_HOME.UC_MAP);	
		}
		
		$bcond     = $this->Ajax->getDataTypes("building_condition");
		$new_bcond = array();
		for($i=0; $i<count($bcond); $i++) {
			if((int)$bcond[$i] > $prop_info['building_condition']){
				$new_bcond[] = $bcond[$i];
			}
		}
		$this->set('property_name',$prop_info['property_name']);
		$this->set('bcond',$new_bcond);
		$this->set('btype', $this->Ajax->getDataTypes("building_type"));
		$this->set('curr_btype',$prop_info['building_type']);
		$this->set('old_bcond',$prop_info['building_condition']);
		$message = "";
		if(isset($this->params['form']) && !empty($this->params['form'])) {
			$required = array('property_name'=>"name for the property", "building_cond"=>"a building condition");
			foreach($required as $req=>$mess){
				if(!isset($this->params['form'][$req]) || 
				empty($this->params['form'][$req])){
					$message .= "- Please select {$mess}.<br/>";
				}
			}
			$upgrade_val = $this->Cron->getValue4Update($this->params['form']['building_cond'],
					$prop_info['building_condition']);
			$this->set('upgrade_val',$upgrade_val);	

			$is_afford = $this->Page->affordable($upgrade_val, $user_id); 
			if(!empty($is_afford)) {
				$message = $is_afford;
			}
			
			//$building_cond, $region_worth, $building_type, $region_id
			
			$upgrade_revenue = $this->Cron->getValue4Revenue($this->params['form']['building_cond'],
				$prop_info['region_worth'],$prop_info['building_type'],$prop_info['region_id']);
			if(empty($message)) {
				$this->Page->upgradeBuilding($this->params['form'],$marker_id, $user_id, 
					$upgrade_val,$upgrade_revenue);
				unset($this->params['form']);
				$this->set('message','Property succesfully upgraded!');
			} else {
				$this->set('message',$message);	
			}
			$this->requestAction('/Cron/createMarkers/');	
		}
		$this->pageTitle = "Upgrade property";
	}
	
	function changeInfo(){
		if(!$this->Session->check('logged')){
			$this->redirect(U_HOME);
		}
		$this->layout = "default";
		$message = '';
		$id = $this->Session->read('logged');
		$details = $this->Login->getDetails($id);
		$this->set('details', $details);	
		if(isset($this->params['form']) && !empty($this->params['form'])){
			if(!empty($this->params['form']['change_send'])){
				//if isset one of the passwords
				if(!empty($this->params['form']['re_password']) || 
					!empty($this->params['form']['password'])){
					$required = array('re_password'=>'Retype password', 'password' =>'Password');
					foreach($required as $req=>$mess){
						if(!isset($this->params['form'][$req]) || 
							empty($this->params['form'][$req])) {
							$message .= '- The "<i>'.$mess.'</i>" field was not filled in<br/>';
						}		
					}
					if($this->params['form']['re_password'] != $this->params['form']['password']) {
						$message .= '- The two passwords do not coincide<br/>';	
					}
				}	
				$required = array('last_name'=>'Last name', 'first_name' =>'First name');
				foreach($required as $req=>$mess){
					if(!isset($this->params['form'][$req]) || 
						empty($this->params['form'][$req])) {
						$message .= '- The "<i>'.$mess.'</i>" field was not filled in<br/>';
					}		
				}
				
				if(empty($message)){	
					$this->Login->changeInfo($id, $this->params['form']);
					$message = "The information was successfully changed";
					//unset($this->params['form']);
				}
			}
		}
		$this->set('message', $message);	
		$this->pageTitle = 'Change Info';	
	}
	
	function destroyProperty($marker_id, $user_id) {
		$user_id = $this->Session->read('logged');
		$this->set('destructs', $this->Ajax->getDataTypes("destruction_name","destruction"));
		if(isset($this->params['form'])&&!empty($this->params['form'])){
			$message = $this->Page->affordable($this->params['form']['destruction_price'], $user_id);
			if(empty($message)){
				$message = $this->Page->buyDestruction($this->params['form'],$marker_id,$user_id);
				$this->set('message','Your destruction was successfully applied!');
				$this->requestAction('/Cron/createMarkers/');	
				unset($this->params['form']);
			}else{
				$this->set('message',$message);
			}
		}
		$this->pageTitle = "Destroy a property";
	}

	function showNews(){
		$this->pageTitle = "News";
	}

	function orderProfilesByNetworth($a, $b) {
		// order net worth of players descending
		if (isset($a['net_worth']) && isset($b['net_worth'])) {
			if ($a['net_worth'] > $b['net_worth']) {return -1;}
			if ($a['net_worth'] < $b['net_worth']) {return 1;}
		}
		return 0;
	}

	function showProfiles(){
		$this->pageTitle = "Profiles";
		$game_id = $this->Session->read('game_id');
		$profiles = $this->Page->userProfiles($game_id);
		foreach($profiles as $userid=>$info){
			if(isset($info['no_props']) && isset($info['total_revenue'])){
				$profiles[$userid]['net_worth'] = $this->Cron->getUserRanking($userid);
			}
			else {
				$profiles[$userid]['net_worth'] = 0;
			}
		}
		usort($profiles, array('PagesController','orderProfilesByNetworth'));
		//var_dump($profiles);
		$this->set('profiles',$profiles);
	}
	
	function showSwarm() {	
		$game_id = $this->Session->read('game_id');
		$this->set("swarm_file", "swarm{$game_id}.js");
		$swarmRegions ="var swarmInfo = new Array();";
		$swarmInfo = $this->Page->getSwarmRegionInfo($game_id);
		foreach($swarmInfo as $reg=>$info){
			$swarmRegions .= "swarmInfo[{$reg}] = \"<p class=\'strong\'>Region: {$reg}</p><br/><br/>";
			foreach($info as $inf){
				$inf["property_name"] = str_replace("'","",$inf["property_name"]);
				$inf["property_name"] = str_replace('"','',$inf["property_name"]);
				$inf["building_type"] = str_replace("'","",$inf["building_type"]);
				$inf["building_type"] = str_replace('"','',$inf["building_type"]);
				$inf['first_name']    = str_replace("'","",$inf["first_name"]);	
				$inf['first_name']    = str_replace('"','',$inf["first_name"]);	
				$inf['last_name']     = str_replace("'","",$inf["last_name"]);
				$inf['last_name']     = str_replace('"','',$inf["last_name"]);	
				$swarmRegions .= "{$inf["building_type"]} >> {$inf["property_name"]} >> <i>Owned by:</i> {$inf['first_name']}{$inf['last_name']}<br/>";
			}		
			$swarmRegions .= "\";";
		}		
		$this->set("swarmRegions", $swarmRegions);	
		$this->pageTitle = "Swarm";
	}

	function showHelp() {
		$this->pageTitle = "Help";
	}
}

